import 'dart:developer' as developer;
import 'package:flutter/foundation.dart';
import 'dart:convert'; // Added for jsonEncode

/// 日志级别
enum LogLevel {
  debug,
  info,
  warning,
  error,
}

/// YHLog 日志系统
class YHLog {
  static final YHLog _instance = YHLog._internal();
  factory YHLog() => _instance;
  YHLog._internal();

  static YHLog get instance => _instance;

  /// 是否启用日志 - 自动与环境关联
  static bool get _enabled => kDebugMode;

  /// 初始化日志系统
  void init({
    bool enabled = true,
    LogLevel minLevel = LogLevel.debug,
  }) {
    // 保持简洁，使用环境自动判断
  }

  /// 调试日志
  static void d(dynamic message, {String? tag}) {
    _log(message, LogLevel.debug, tag: tag);
  }

  /// 信息日志
  static void i(dynamic message, {String? tag}) {
    _log(message, LogLevel.info, tag: tag);
  }

  /// 警告日志
  static void w(dynamic message, {String? tag}) {
    _log(message, LogLevel.warning, tag: tag);
  }

  /// 错误日志
  static void e(dynamic message, {String? tag, Object? error, StackTrace? stackTrace}) {
    _log(message, LogLevel.error, tag: tag, error: error, stackTrace: stackTrace);
  }

  /// 内部日志打印方法
  static void _log(
    dynamic message,
    LogLevel level, {
    String? tag,
    Object? error,
    StackTrace? stackTrace,
  }) {
    if (!_enabled || !kDebugMode) return;

    /// 获取调用栈信息
    final currentStackTrace = StackTrace.current;
    final stackList = currentStackTrace.toString().split('\n');

    /// 获取调用者信息（跳过前两个栈帧：_log 和 d/i/w/e 方法）
    String callerInfo = 'Unknown';
    if (stackList.length > 2) {
      final callerLine = stackList[2].trim();
      /// 匹配格式: #0   _MyHomePageState.build (package:my_app/pages/home_page.dart:25:3)
      final match = RegExp(r'(.*) \((.+):([0-9]+)').firstMatch(callerLine);
      if (match != null) {
        final file = match.group(2)?.split('/').last ?? 'unknown';
        final line = match.group(3) ?? '0';
        callerInfo = '$file:$line';
      }
    }

    // 日志级别前缀
    String prefix = '';
    switch (level) {
      case LogLevel.debug:
        prefix = '💙D/ ';
        break;
      case LogLevel.info:
        prefix = '💚I/ ';
        break;
      case LogLevel.warning:
        prefix = '💛W/ ';
        break;
      case LogLevel.error:
        prefix = '❤️E/ ';
        break;
    }

    // 添加标签
    final tagStr = tag != null ? '[$tag] ' : '';

    // 构建日志消息
    String logMessage = '$prefix$tagStr$callerInfo  $message';
    
    // 如果有错误，添加到日志中
    // if (error != null) {
    //   logMessage += '\n❌错误详情: $error';
    // }

    // 打印日志
    developer.log(logMessage, name: 'YHLog');
  }

  /// 打印对象的详细信息
  static void printObject(Object? object, {String? tag}) {
    if (object == null) {
      d('对象为 null', tag: tag);
      return;
    }
    try {
      final jsonString = jsonEncode(object);
      d('对象内容: $jsonString', tag: tag);
    } catch (e) {
      d('对象内容: $object', tag: tag);
      d('对象类型: ${object.runtimeType}', tag: tag);
      d('无法转换为 JSON: $e', tag: tag);
    }
  }
}
